const fs = require("fs");
const { Liquid } = require("liquidjs");
const tags = require("./tags");
const filters = require("./filters");
const { globals } = require("../mock/");
const { replaceComponentName } = require("../util/index");
// const { createLiquid,createStyle,createJavascript } = require("./index");

const nodeSass = require("node-sass");

function readFile(file) {
    return fs.readFileSync(file, "utf-8");
}

const readNodeSass = function (filePath) {
    const content = readFile(filePath);
    if (content) {
        return nodeSass.renderSync({
            data: content
        }).css;
    }
    return "";
};




/**
 * @description: 获取文件内容组合 
 * html replaceComponentName 做组件名称替换
 * js replaceComponentName 做组件名称替换
 * scss readNodeSass 编译
 * @param {*} file 文件路径
 * @return {*} html
 */
function createLiquid(file){
    let html = replaceComponentName(readFile(file),file);
    let scss = readNodeSass(file.replace('liquid','scss'));
    let js = replaceComponentName( readFile(file.replace('liquid','js')),file);
    //替换_COMPONENT_NAME_环境变量为当前路由
    js = js ? `<script type="text/javascript">${js}</script>` : "";
    scss = scss ? `<style>${scss}</style>` : "";

    return `${scss}${js}${html}`
}


const engine = new Liquid({
    root: __dirname, // for layouts and partials
    relativeReference: false,
    globals:globals,
    fs: {
        readFileSync(file) {
            return createLiquid(file)
        },
        readFile(file) {
            return fs.readFileSync(file, "utf-8");
        },
        existsSync() {
            return true;
        },
        exists() {
            return true;
        },
        resolve(root, file, ext) {
            return file;
        }
    }
});
tags(engine);
filters(engine);

module.exports = engine;
